﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using DTcms.API.Payment.wxpay;
using DTcms.Common;

namespace DTcms.Web.Mvc.api.payment.wxh5pay
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //获得订单信息
            int site_payment_id = 0; //订单支付方式
            Model.siteconfig sysConfig = new BLL.siteconfig().loadConfig();
            string order_no = DTRequest.GetFormString("pay_order_no").ToUpper();
            decimal order_amount = DTRequest.GetFormDecimal("pay_order_amount", 0);
            string user_name = DTRequest.GetFormString("pay_user_name");
            string subject = DTRequest.GetFormString("pay_subject");

            //检查参数是否正确
            if (string.IsNullOrEmpty(order_no) || order_amount == 0)
            {
                Response.Redirect(UrlHelperExtend.linkurl("error", "?msg=" + Utils.UrlEncode("对不起，您提交的参数有误！")));
                return;
            }
            //===============================判断订单==================================
            if (order_no.StartsWith("R")) //R开头为在线充值订单
            {
                Model.user_recharge model = new BLL.user_recharge().GetModel(order_no);
                if (model == null)
                {
                    Response.Redirect(UrlHelperExtend.linkurl("error", "?msg=" + Utils.UrlEncode("对不起，您充值的订单号不存在或已删除！")));
                    return;
                }
                if (model.amount != order_amount)
                {
                    Response.Redirect(UrlHelperExtend.linkurl("error", "?msg=" + Utils.UrlEncode("对不起，您充值的订单金额与实际金额不一致！")));
                    return;
                }
                site_payment_id = model.payment_id; //站点支付方式ID
            }
            else //B开头为商品订单
            {
                Response.Redirect(UrlHelperExtend.linkurl("error", "?msg=" + Utils.UrlEncode("B开头为商品订单功能弃用！")));
                return;
            }
            if (user_name != "")
            {
                user_name = "支付会员：" + user_name;
            }
            else
            {
                user_name = "匿名用户";
            }

            //===========================调用统一下单接口==============================
            string sendUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            H5ApiConfig h5Config = new H5ApiConfig(site_payment_id);
            WxPayData data = new WxPayData();
            data.SetValue("body", sysConfig.webname + "-" + subject); //商品描述
            data.SetValue("detail", user_name); //商品详情
            data.SetValue("out_trade_no", order_no); //商户订单号
            data.SetValue("total_fee", (Convert.ToDouble(order_amount) * 100).ToString()); //订单总金额,以分为单位
            data.SetValue("trade_type", "MWEB");//交易类型
            data.SetValue("product_id", order_no);//商品ID
            data.SetValue("notify_url", h5Config.Notify_url); //异步通知url
            data.SetValue("spbill_create_ip", DTRequest.GetIP()); //终端IP
            data.SetValue("appid", h5Config.AppId); //公众账号ID
            data.SetValue("mch_id", h5Config.Partner); //商户号
            data.SetValue("nonce_str", H5ApiPay.GenerateNonceStr()); //随机字符串
            data.SetValue("scene_info", "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":\"" + sysConfig.weburl + "\",\"wap_name\":\"" + sysConfig.webname + "\"}}"); //场景信息
            data.SetValue("sign", data.MakeSign(h5Config.Key)); //签名
            string xml = data.ToXml(); //转换成XML
            var startTime = DateTime.Now; //开始时间
            string response = HttpService.Post(xml, sendUrl, false, 6); //发送请求
            var endTime = DateTime.Now; //结束时间
            int timeCost = (int)((endTime - startTime).TotalMilliseconds); //计算所用时间
            WxPayData result = new WxPayData();
            H5ApiPay.ReportCostTime(site_payment_id, sendUrl, timeCost, result); //测速上报
            result.FromXml(response, h5Config.Key);
            string returnCode = result.GetValue("return_code").ToString();
            //成功状态
            if (returnCode == "SUCCESS")
            {
                string resultCode = result.GetValue("result_code").ToString();
                if (resultCode == "SUCCESS")
                {
                    //跳转到支付链接
                    Response.Redirect(result.GetValue("mweb_url").ToString());
                    return;
                }
                else
                {
                    Response.Redirect(UrlHelperExtend.linkurl("error", "?msg=" + Utils.UrlEncode("支付错误：" + result.GetValue("err_code_des"))));
                    return;
                }
            }
            else
            {
                Response.Redirect(UrlHelperExtend.linkurl("error", "?msg=" + Utils.UrlEncode("支付错误：" + result.GetValue("return_msg"))));
                return;
            }

        }
    }
}